package com.xwb.config;

import com.xwb.entity.User;
import com.xwb.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

@Slf4j
public class ShiroFilter extends FormAuthenticationFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        //这里只有返回false才会执行onAccessDenied方法,因为
        // return super.isAccessAllowed(request, response, mappedValue);
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {

        String token = getRequestToken((HttpServletRequest) request);
        String urlPath = ((HttpServletRequest) request).getServletPath();

        //如果为登录请求,就放行
        if ("/login".equals(urlPath)||"/register".equals(urlPath)){
            log.info("放行");
            return true;
        }
        //如果为登录页面请求,就放行
        if ("/tologinPage".equals(urlPath)||"/".equals(urlPath)){
            log.info("放行");
            return true;
        }
        //查看swagger放行
        if(urlPath.contains("/swagger")||urlPath.contains("/v2")||urlPath.contains("/csrf")){
            log.info("放行");
            return true;
        }

        if (token==null){
            log.error("没有token");
            return true;
        }

        //从当前shiro中获得用户信息
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        //拿到redis的token
        String o = (String) RedisUtils.redisTemplate.opsForValue().get(user.getUsername());
        // 一致直通过
        if (o.equals(token)){
            return true;
        }else if(o==null){
            log.error("token失效");
        }else if(!o.equals(token)){
            log.error("token不正确");
        }
        return false;
    }

    private String getRequestToken(HttpServletRequest request){
        //默认从请求头中获得token
        //return request.getParameter("token");
        return request.getHeader("token");

    }
}

